<!-- HTML header for doxygen 1.8.6-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.13"/>
<title>OpenCV: File Input and Output using XML and YAML files</title>
<link href="../../opencv.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../jquery.js"></script>
<script type="text/javascript" src="../../dynsections.js"></script>
<script type="text/javascript" src="../../tutorial-utils.js"></script>
<link href="../../search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="../../search/searchdata.js"></script>
<script type="text/javascript" src="../../search/search.js"></script>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    extensions: ["tex2jax.js", "TeX/AMSmath.js", "TeX/AMSsymbols.js"],
    jax: ["input/TeX","output/HTML-CSS"],
});
//<![CDATA[
MathJax.Hub.Config(
{
  TeX: {
      Macros: {
          matTT: [ "\\[ \\left|\\begin{array}{ccc} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{array}\\right| \\]", 9],
          fork: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ \\end{array} \\right.", 4],
          forkthree: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ \\end{array} \\right.", 6],
          forkfour: ["\\left\\{ \\begin{array}{l l} #1 & \\mbox{#2}\\\\ #3 & \\mbox{#4}\\\\ #5 & \\mbox{#6}\\\\ #7 & \\mbox{#8}\\\\ \\end{array} \\right.", 8],
          vecthree: ["\\begin{bmatrix} #1\\\\ #2\\\\ #3 \\end{bmatrix}", 3],
          vecthreethree: ["\\begin{bmatrix} #1 & #2 & #3\\\\ #4 & #5 & #6\\\\ #7 & #8 & #9 \\end{bmatrix}", 9],
          cameramatrix: ["#1 = \\begin{bmatrix} f_x & 0 & c_x\\\\ 0 & f_y & c_y\\\\ 0 & 0 & 1 \\end{bmatrix}", 1],
          distcoeffs: ["(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6 [, s_1, s_2, s_3, s_4[, \\tau_x, \\tau_y]]]]) \\text{ of 4, 5, 8, 12 or 14 elements}"],
          distcoeffsfisheye: ["(k_1, k_2, k_3, k_4)"],
          hdotsfor: ["\\dots", 1],
          mathbbm: ["\\mathbb{#1}", 1],
          bordermatrix: ["\\matrix{#1}", 1]
      }
  }
}
);
//]]>
</script><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js"></script>
<link href="../../doxygen.css" rel="stylesheet" type="text/css" />
<link href="../../stylesheet.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<!--#include virtual="/google-search.html"-->
<table cellspacing="0" cellpadding="0">
 <tbody>
 <tr style="height: 56px;">
  <td id="projectlogo"><img alt="Logo" src="../../opencv-logo-small.png"/></td>
  <td style="padding-left: 0.5em;">
   <div id="projectname">OpenCV
   &#160;<span id="projectnumber">4.5.2</span>
   </div>
   <div id="projectbrief">Open Source Computer Vision</div>
  </td>
 </tr>
 </tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.13 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "../../search",false,'Search');
</script>
<script type="text/javascript" src="../../menudata.js"></script>
<script type="text/javascript" src="../../menu.js"></script>
<script type="text/javascript">
$(function() {
  initMenu('../../',true,false,'search.php','Search');
  $(document).ready(function() { init_search(); });
});
</script>
<div id="main-nav"></div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
     onmouseover="return searchBox.OnSearchSelectShow()"
     onmouseout="return searchBox.OnSearchSelectHide()"
     onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>

<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0" 
        name="MSearchResults" id="MSearchResults">
</iframe>
</div>

<div id="nav-path" class="navpath">
  <ul>
<li class="navelem"><a class="el" href="../../d9/df8/tutorial_root.html">OpenCV Tutorials</a></li><li class="navelem"><a class="el" href="../../de/d7a/tutorial_table_of_content_core.html">The Core Functionality (core module)</a></li>  </ul>
</div>
</div><!-- top -->
<div class="header">
  <div class="headertitle">
<div class="title">File Input and Output using XML and YAML files </div>  </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><p><b>Prev Tutorial:</b> <a class="el" href="../../d8/d01/tutorial_discrete_fourier_transform.html">Discrete Fourier Transform</a></p>
<p><b>Next Tutorial:</b> <a class="el" href="../../d7/dff/tutorial_how_to_use_OpenCV_parallel_for_.html">How to use the OpenCV parallel_for_ to parallelize your code</a></p>
<table class="doxtable">
<tr>
<th align="right"></th><th align="left"></th></tr>
<tr>
<td align="right">Original author </td><td align="left">Bernát Gábor </td></tr>
<tr>
<td align="right">Compatibility </td><td align="left">OpenCV &gt;= 3.0 </td></tr>
</table>
<h2>Goal </h2>
<p>You'll find answers for the following questions:</p>
<ul>
<li>How to print and read text entries to a file and OpenCV using YAML or XML files?</li>
<li>How to do the same for OpenCV data structures?</li>
<li>How to do this for your data structures?</li>
<li>Usage of OpenCV data structures such as <a class="el" href="../../da/d56/classcv_1_1FileStorage.html">cv::FileStorage</a> , <a class="el" href="../../de/dd9/classcv_1_1FileNode.html">cv::FileNode</a> or <a class="el" href="../../d7/d4e/classcv_1_1FileNodeIterator.html">cv::FileNodeIterator</a> .</li>
</ul>
<h2>Source code </h2>
 <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> You can <a href="https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp">download this from here</a> or find it in the <code>samples/cpp/tutorial_code/core/file_input_output/file_input_output.cpp</code> of the OpenCV source code library.</p>
<p>Here's a sample code of how to achieve all the stuff enumerated at the goal list.</p>
<div class="fragment"><div class="line"><span class="preprocessor">#include &lt;<a class="code" href="../../d0/d9c/core_2include_2opencv2_2core_8hpp.html">opencv2/core.hpp</a>&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;iostream&gt;</span></div><div class="line"><span class="preprocessor">#include &lt;string&gt;</span></div><div class="line"></div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d2/d75/namespacecv.html">cv</a>;</div><div class="line"><span class="keyword">using namespace </span><a class="code" href="../../d8/dcc/namespacestd.html">std</a>;</div><div class="line"></div><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> help(<span class="keywordtype">char</span>** av)</div><div class="line">{</div><div class="line">    cout &lt;&lt; endl</div><div class="line">        &lt;&lt; av[0] &lt;&lt; <span class="stringliteral">&quot; shows the usage of the OpenCV serialization functionality.&quot;</span>         &lt;&lt; endl</div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;usage: &quot;</span>                                                                      &lt;&lt; endl</div><div class="line">        &lt;&lt;  av[0] &lt;&lt; <span class="stringliteral">&quot; outputfile.yml.gz&quot;</span>                                                 &lt;&lt; endl</div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;The output file may be either XML (xml) or YAML (yml/yaml). You can even compress it by &quot;</span></div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;specifying this in its extension like xml.gz yaml.gz etc... &quot;</span>                  &lt;&lt; endl</div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;With FileStorage you can serialize objects in OpenCV by using the &lt;&lt; and &gt;&gt; operators&quot;</span> &lt;&lt; endl</div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;For example: - create a class and have it serialized&quot;</span>                         &lt;&lt; endl</div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;             - use it to read and write matrices.&quot;</span>                            &lt;&lt; endl;</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keyword">class </span>MyData</div><div class="line">{</div><div class="line"><span class="keyword">public</span>:</div><div class="line">    MyData() : A(0), X(0), id()</div><div class="line">    {}</div><div class="line">    <span class="keyword">explicit</span> MyData(<span class="keywordtype">int</span>) : A(97), X(<a class="code" href="../../db/de0/group__core__utils.html#ga677b89fae9308b340ddaebf0dba8455f">CV_PI</a>), id(<span class="stringliteral">&quot;mydata1234&quot;</span>) <span class="comment">// explicit to avoid implicit conversion</span></div><div class="line">    {}</div><div class="line">    <span class="keywordtype">void</span> <a class="code" href="../../d2/d75/namespacecv.html#a027b764f14e54f8838b5120e991bd29c">write</a>(<a class="code" href="../../da/d56/classcv_1_1FileStorage.html">FileStorage</a>&amp; fs) <span class="keyword">const</span>                        <span class="comment">//Write serialization for this class</span></div><div class="line">    {</div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;{&quot;</span> &lt;&lt; <span class="stringliteral">&quot;A&quot;</span> &lt;&lt; A &lt;&lt; <span class="stringliteral">&quot;X&quot;</span> &lt;&lt; X &lt;&lt; <span class="stringliteral">&quot;id&quot;</span> &lt;&lt; <span class="keywordtype">id</span> &lt;&lt; <span class="stringliteral">&quot;}&quot;</span>;</div><div class="line">    }</div><div class="line">    <span class="keywordtype">void</span> <a class="code" href="../../d2/d75/namespacecv.html#a9afba2f5b9bf298c62da8cf66184e41f">read</a>(<span class="keyword">const</span> <a class="code" href="../../de/dd9/classcv_1_1FileNode.html">FileNode</a>&amp; node)                          <span class="comment">//Read serialization for this class</span></div><div class="line">    {</div><div class="line">        A = (int)node[<span class="stringliteral">&quot;A&quot;</span>];</div><div class="line">        X = (double)node[<span class="stringliteral">&quot;X&quot;</span>];</div><div class="line">        <span class="keywordtype">id</span> = (string)node[<span class="stringliteral">&quot;id&quot;</span>];</div><div class="line">    }</div><div class="line"><span class="keyword">public</span>:   <span class="comment">// Data Members</span></div><div class="line">    <span class="keywordtype">int</span> A;</div><div class="line">    <span class="keywordtype">double</span> X;</div><div class="line">    <span class="keywordtype">string</span> id;</div><div class="line">};</div><div class="line"></div><div class="line"><span class="comment">//These write and read functions must be defined for the serialization in FileStorage to work</span></div><div class="line"><span class="comment"></span><span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="../../d2/d75/namespacecv.html#a027b764f14e54f8838b5120e991bd29c">write</a>(<a class="code" href="../../da/d56/classcv_1_1FileStorage.html">FileStorage</a>&amp; fs, <span class="keyword">const</span> std::string&amp;, <span class="keyword">const</span> MyData&amp; x)</div><div class="line">{</div><div class="line">    x.write(fs);</div><div class="line">}</div><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="../../d2/d75/namespacecv.html#a9afba2f5b9bf298c62da8cf66184e41f">read</a>(<span class="keyword">const</span> <a class="code" href="../../de/dd9/classcv_1_1FileNode.html">FileNode</a>&amp; node, MyData&amp; x, <span class="keyword">const</span> MyData&amp; default_value = MyData()){</div><div class="line">    <span class="keywordflow">if</span>(node.<a class="code" href="../../de/dd9/classcv_1_1FileNode.html#a82d59aab4765da6140c238c54aadfa92">empty</a>())</div><div class="line">        x = default_value;</div><div class="line">    <span class="keywordflow">else</span></div><div class="line">        x.read(node);</div><div class="line">}</div><div class="line"></div><div class="line"><span class="comment">// This function will print our custom class to the console</span></div><div class="line"><span class="keyword">static</span> ostream&amp; <a class="code" href="../../d0/de1/group__core.html#gafdef54942b265b663de6bbc789d306e4">operator&lt;&lt;</a>(ostream&amp; out, <span class="keyword">const</span> MyData&amp; m)</div><div class="line">{</div><div class="line">    out &lt;&lt; <span class="stringliteral">&quot;{ id = &quot;</span> &lt;&lt; m.id &lt;&lt; <span class="stringliteral">&quot;, &quot;</span>;</div><div class="line">    out &lt;&lt; <span class="stringliteral">&quot;X = &quot;</span> &lt;&lt; m.X &lt;&lt; <span class="stringliteral">&quot;, &quot;</span>;</div><div class="line">    out &lt;&lt; <span class="stringliteral">&quot;A = &quot;</span> &lt;&lt; m.A &lt;&lt; <span class="stringliteral">&quot;}&quot;</span>;</div><div class="line">    <span class="keywordflow">return</span> out;</div><div class="line">}</div><div class="line"></div><div class="line"><span class="keywordtype">int</span> main(<span class="keywordtype">int</span> ac, <span class="keywordtype">char</span>** av)</div><div class="line">{</div><div class="line">    <span class="keywordflow">if</span> (ac != 2)</div><div class="line">    {</div><div class="line">        help(av);</div><div class="line">        <span class="keywordflow">return</span> 1;</div><div class="line">    }</div><div class="line"></div><div class="line">    <span class="keywordtype">string</span> filename = av[1];</div><div class="line">    { <span class="comment">//write</span></div><div class="line"><span class="comment"></span>        <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> R = <a class="code" href="../../df/dfc/classcv_1_1Mat__.html#a992daefd1a256fbd40423a2cf77f42a1">Mat_&lt;uchar&gt;::eye</a>(3, 3),</div><div class="line">            T = <a class="code" href="../../df/dfc/classcv_1_1Mat__.html#ab68de1358f5aedd6028269f77a9e841b">Mat_&lt;double&gt;::zeros</a>(3, 1);</div><div class="line">        MyData m(1);</div><div class="line"></div><div class="line">        <a class="code" href="../../da/d56/classcv_1_1FileStorage.html">FileStorage</a> fs(filename, <a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a973e41cb75ef6230412a567723b7482da747a241cefee7b8af34c3d804c864ad6">FileStorage::WRITE</a>);</div><div class="line">        <span class="comment">// or:</span></div><div class="line">        <span class="comment">// FileStorage fs;</span></div><div class="line">        <span class="comment">// fs.open(filename, FileStorage::WRITE);</span></div><div class="line"><span class="comment"></span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;iterationNr&quot;</span> &lt;&lt; 100;</div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;strings&quot;</span> &lt;&lt; <span class="stringliteral">&quot;[&quot;</span>;                              <span class="comment">// text - string sequence</span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;image1.jpg&quot;</span> &lt;&lt; <span class="stringliteral">&quot;Awesomeness&quot;</span> &lt;&lt; <span class="stringliteral">&quot;../data/baboon.jpg&quot;</span>;</div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;]&quot;</span>;                                           <span class="comment">// close sequence</span></div><div class="line"><span class="comment"></span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;Mapping&quot;</span>;                              <span class="comment">// text - mapping</span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;{&quot;</span> &lt;&lt; <span class="stringliteral">&quot;One&quot;</span> &lt;&lt; 1;</div><div class="line">        fs &lt;&lt;        <span class="stringliteral">&quot;Two&quot;</span> &lt;&lt; 2 &lt;&lt; <span class="stringliteral">&quot;}&quot;</span>;</div><div class="line"></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;R&quot;</span> &lt;&lt; R;                                      <span class="comment">// cv::Mat</span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;T&quot;</span> &lt;&lt; T;</div><div class="line"></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;MyData&quot;</span> &lt;&lt; m;                                <span class="comment">// your own data structures</span></div><div class="line"><span class="comment"></span></div><div class="line">        fs.<a class="code" href="../../da/d56/classcv_1_1FileStorage.html#ad23d5415a06fb4bc97bfa034589b376e">release</a>();                                       <span class="comment">// explicit close</span></div><div class="line"><span class="comment"></span>        cout &lt;&lt; <span class="stringliteral">&quot;Write Done.&quot;</span> &lt;&lt; endl;</div><div class="line">    }</div><div class="line"></div><div class="line">    {<span class="comment">//read</span></div><div class="line">        cout &lt;&lt; endl &lt;&lt; <span class="stringliteral">&quot;Reading: &quot;</span> &lt;&lt; endl;</div><div class="line">        <a class="code" href="../../da/d56/classcv_1_1FileStorage.html">FileStorage</a> fs;</div><div class="line">        fs.<a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a14c2c18dc2e29999d03d52a0c24bd91c">open</a>(filename, <a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a973e41cb75ef6230412a567723b7482daa0dcc459c4d100c35ccfa9a643827bed">FileStorage::READ</a>);</div><div class="line"></div><div class="line">        <span class="keywordtype">int</span> itNr;</div><div class="line">        <span class="comment">//fs[&quot;iterationNr&quot;] &gt;&gt; itNr;</span></div><div class="line">        itNr = (int) fs[<span class="stringliteral">&quot;iterationNr&quot;</span>];</div><div class="line">        cout &lt;&lt; itNr;</div><div class="line">        <span class="keywordflow">if</span> (!fs.<a class="code" href="../../da/d56/classcv_1_1FileStorage.html#aa952c31f4e632595cd5ac107913f4fd1">isOpened</a>())</div><div class="line">        {</div><div class="line">            cerr &lt;&lt; <span class="stringliteral">&quot;Failed to open &quot;</span> &lt;&lt; filename &lt;&lt; endl;</div><div class="line">            help(av);</div><div class="line">            <span class="keywordflow">return</span> 1;</div><div class="line">        }</div><div class="line"></div><div class="line">        <a class="code" href="../../de/dd9/classcv_1_1FileNode.html">FileNode</a> n = fs[<span class="stringliteral">&quot;strings&quot;</span>];                         <span class="comment">// Read string sequence - Get node</span></div><div class="line">        <span class="keywordflow">if</span> (n.<a class="code" href="../../de/dd9/classcv_1_1FileNode.html#ad0fd448e25719a94320ebe574b87f997">type</a>() != <a class="code" href="../../de/dd9/classcv_1_1FileNode.html#a296580c68b764fddeb2cd42912bd34ccaa359c2282183738d11a665035a1a67bb">FileNode::SEQ</a>)</div><div class="line">        {</div><div class="line">            cerr &lt;&lt; <span class="stringliteral">&quot;strings is not a sequence! FAIL&quot;</span> &lt;&lt; endl;</div><div class="line">            <span class="keywordflow">return</span> 1;</div><div class="line">        }</div><div class="line"></div><div class="line">        <a class="code" href="../../d7/d4e/classcv_1_1FileNodeIterator.html">FileNodeIterator</a> it = n.<a class="code" href="../../de/dd9/classcv_1_1FileNode.html#a0f299820227506079f5b9013dd8c3558">begin</a>(), it_end = n.<a class="code" href="../../de/dd9/classcv_1_1FileNode.html#a58b033e34726eb73f0238a1bfbe0c8e9">end</a>(); <span class="comment">// Go through the node</span></div><div class="line">        <span class="keywordflow">for</span> (; it != it_end; ++it)</div><div class="line">            cout &lt;&lt; (<span class="keywordtype">string</span>)*it &lt;&lt; endl;</div><div class="line"></div><div class="line"></div><div class="line">        n = fs[<span class="stringliteral">&quot;Mapping&quot;</span>];                                <span class="comment">// Read mappings from a sequence</span></div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Two  &quot;</span> &lt;&lt; (int)(n[<span class="stringliteral">&quot;Two&quot;</span>]) &lt;&lt; <span class="stringliteral">&quot;; &quot;</span>;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;One  &quot;</span> &lt;&lt; (int)(n[<span class="stringliteral">&quot;One&quot;</span>]) &lt;&lt; endl &lt;&lt; endl;</div><div class="line"></div><div class="line"></div><div class="line">        MyData m;</div><div class="line">        <a class="code" href="../../d3/d63/classcv_1_1Mat.html">Mat</a> R, T;</div><div class="line"></div><div class="line">        fs[<span class="stringliteral">&quot;R&quot;</span>] &gt;&gt; R;                                      <span class="comment">// Read cv::Mat</span></div><div class="line">        fs[<span class="stringliteral">&quot;T&quot;</span>] &gt;&gt; T;</div><div class="line">        fs[<span class="stringliteral">&quot;MyData&quot;</span>] &gt;&gt; m;                                 <span class="comment">// Read your own structure_</span></div><div class="line"><span class="comment"></span></div><div class="line">        cout &lt;&lt; endl</div><div class="line">            &lt;&lt; <span class="stringliteral">&quot;R = &quot;</span> &lt;&lt; R &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;T = &quot;</span> &lt;&lt; T &lt;&lt; endl &lt;&lt; endl;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;MyData = &quot;</span> &lt;&lt; endl &lt;&lt; m &lt;&lt; endl &lt;&lt; endl;</div><div class="line"></div><div class="line">        <span class="comment">//Show default behavior for non existing nodes</span></div><div class="line"><span class="comment"></span>        cout &lt;&lt; <span class="stringliteral">&quot;Attempt to read NonExisting (should initialize the data structure with its default).&quot;</span>;</div><div class="line">        fs[<span class="stringliteral">&quot;NonExisting&quot;</span>] &gt;&gt; m;</div><div class="line">        cout &lt;&lt; endl &lt;&lt; <span class="stringliteral">&quot;NonExisting = &quot;</span> &lt;&lt; endl &lt;&lt; m &lt;&lt; endl;</div><div class="line">    }</div><div class="line"></div><div class="line">    cout &lt;&lt; endl</div><div class="line">        &lt;&lt; <span class="stringliteral">&quot;Tip: Open up &quot;</span> &lt;&lt; filename &lt;&lt; <span class="stringliteral">&quot; with a text editor to see the serialized data.&quot;</span> &lt;&lt; endl;</div><div class="line"></div><div class="line">    <span class="keywordflow">return</span> 0;</div><div class="line">}</div></div><!-- fragment -->  </div>  <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'><p> You can <a href="https://github.com/opencv/opencv/tree/master/samples/python/tutorial_code/core/file_input_output/file_input_output.py">download this from here</a> or find it in the <code>samples/python/tutorial_code/core/file_input_output/file_input_output.py</code> of the OpenCV source code library.</p>
<p>Here's a sample code of how to achieve all the stuff enumerated at the goal list.</p>
<div class="fragment"><div class="line"><span class="keyword">from</span> __future__ <span class="keyword">import</span> print_function</div><div class="line"></div><div class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</div><div class="line"><span class="keyword">import</span> cv2 <span class="keyword">as</span> cv</div><div class="line"><span class="keyword">import</span> sys</div><div class="line"></div><div class="line"><span class="keyword">def </span>help(filename):</div><div class="line">    <span class="keywordflow">print</span> (</div><div class="line">        <span class="stringliteral">&#39;&#39;&#39;</span></div><div class="line"><span class="stringliteral">        {0} shows the usage of the OpenCV serialization functionality. \n\n</span></div><div class="line"><span class="stringliteral">        usage:\n</span></div><div class="line"><span class="stringliteral">            python3 {0} outputfile.yml.gz\n\n</span></div><div class="line"><span class="stringliteral">        The output file may be either in XML, YAML or JSON. You can even compress it\n</span></div><div class="line"><span class="stringliteral">        by specifying this in its extension like xml.gz yaml.gz etc... With\n</span></div><div class="line"><span class="stringliteral">        FileStorage you can serialize objects in OpenCV.\n\n</span></div><div class="line"><span class="stringliteral">        For example: - create a class and have it serialized\n</span></div><div class="line"><span class="stringliteral">                     - use it to read and write matrices.\n</span></div><div class="line"><span class="stringliteral">        &#39;&#39;&#39;</span>.format(filename)</div><div class="line">    )</div><div class="line"></div><div class="line"><span class="keyword">class </span>MyData:</div><div class="line">    A = 97</div><div class="line">    X = np.pi</div><div class="line">    name = <span class="stringliteral">&#39;mydata1234&#39;</span></div><div class="line"></div><div class="line">    <span class="keyword">def </span>__repr__(self):</div><div class="line">        s = <span class="stringliteral">&#39;{ name = &#39;</span> + self.name + <span class="stringliteral">&#39;, X = &#39;</span> + str(self.X)</div><div class="line">        s = s + <span class="stringliteral">&#39;, A = &#39;</span> +  str(self.A) + <span class="stringliteral">&#39;}&#39;</span></div><div class="line">        <span class="keywordflow">return</span> s</div><div class="line"></div><div class="line">    </div><div class="line">    <span class="keyword">def </span><a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a26447446dd3fa0644684a045e16399fe">write</a>(self, fs, name):</div><div class="line">        fs.startWriteStruct(name, cv.FileNode_MAP|cv.FileNode_FLOW)</div><div class="line">        fs.write(<span class="stringliteral">&#39;A&#39;</span>, self.A)</div><div class="line">        fs.write(<span class="stringliteral">&#39;X&#39;</span>, self.X)</div><div class="line">        fs.write(<span class="stringliteral">&#39;name&#39;</span>, self.name)</div><div class="line">        fs.endWriteStruct()</div><div class="line"></div><div class="line">    <span class="keyword">def </span><a class="code" href="../../de/dd9/classcv_1_1FileNode.html#ab24433dde37f770766481a91983e5f44">read</a>(self, node):</div><div class="line">        <span class="keywordflow">if</span> (<span class="keywordflow">not</span> node.empty()):</div><div class="line">            self.A = int(node.getNode(<span class="stringliteral">&#39;A&#39;</span>).real())</div><div class="line">            self.X = node.getNode(<span class="stringliteral">&#39;X&#39;</span>).real()</div><div class="line">            self.name = node.getNode(<span class="stringliteral">&#39;name&#39;</span>).string()</div><div class="line">        <span class="keywordflow">else</span>:</div><div class="line">            self.A = self.X = 0</div><div class="line">            self.name = <span class="stringliteral">&#39;&#39;</span></div><div class="line">    </div><div class="line"></div><div class="line"><span class="keyword">def </span>main(argv):</div><div class="line">    <span class="keywordflow">if</span> len(argv) != 2:</div><div class="line">        help(argv[0])</div><div class="line">        exit(1)</div><div class="line"></div><div class="line">    <span class="comment"># write</span></div><div class="line">    </div><div class="line">    R = np.eye(3,3)</div><div class="line">    T = np.zeros((3,1))</div><div class="line">    </div><div class="line">    m = MyData()</div><div class="line">    </div><div class="line"></div><div class="line">    filename = argv[1]</div><div class="line"></div><div class="line">    </div><div class="line">    s = <a class="code" href="../../da/d56/classcv_1_1FileStorage.html">cv.FileStorage</a>(filename, cv.FileStorage_WRITE)</div><div class="line">    <span class="comment"># or:</span></div><div class="line">    <span class="comment"># s = cv.FileStorage()</span></div><div class="line">    <span class="comment"># s.open(filename, cv.FileStorage_WRITE)</span></div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    s.write(<span class="stringliteral">&#39;iterationNr&#39;</span>, 100)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    s.startWriteStruct(<span class="stringliteral">&#39;strings&#39;</span>, cv.FileNode_SEQ)</div><div class="line">    <span class="keywordflow">for</span> elem <span class="keywordflow">in</span> [<span class="stringliteral">&#39;image1.jpg&#39;</span>, <span class="stringliteral">&#39;Awesomeness&#39;</span>, <span class="stringliteral">&#39;../data/baboon.jpg&#39;</span>]:</div><div class="line">        s.write(<span class="stringliteral">&#39;&#39;</span>, elem)</div><div class="line">    s.endWriteStruct()</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    s.startWriteStruct(<span class="stringliteral">&#39;Mapping&#39;</span>, cv.FileNode_MAP)</div><div class="line">    s.write(<span class="stringliteral">&#39;One&#39;</span>, 1)</div><div class="line">    s.write(<span class="stringliteral">&#39;Two&#39;</span>, 2)</div><div class="line">    s.endWriteStruct()</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    s.write(<span class="stringliteral">&#39;R_MAT&#39;</span>, R)</div><div class="line">    s.write(<span class="stringliteral">&#39;T_MAT&#39;</span>, T)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    m.write(s, <span class="stringliteral">&#39;MyData&#39;</span>)</div><div class="line">    </div><div class="line">    s.release()</div><div class="line">    </div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Write Done.&#39;</span>)</div><div class="line"></div><div class="line">    <span class="comment"># read</span></div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;\nReading: &#39;</span>)</div><div class="line">    s = <a class="code" href="../../da/d56/classcv_1_1FileStorage.html">cv.FileStorage</a>()</div><div class="line">    s.open(filename, cv.FileStorage_READ)</div><div class="line"></div><div class="line">    </div><div class="line">    n = s.getNode(<span class="stringliteral">&#39;iterationNr&#39;</span>)</div><div class="line">    itNr = int(n.real())</div><div class="line">    </div><div class="line">    <span class="keywordflow">print</span> (itNr)</div><div class="line"></div><div class="line">    <span class="keywordflow">if</span> (<span class="keywordflow">not</span> s.isOpened()):</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Failed to open &#39;</span>, filename, file=sys.stderr)</div><div class="line">        help(argv[0])</div><div class="line">        exit(1)</div><div class="line"></div><div class="line">    </div><div class="line">    n = s.getNode(<span class="stringliteral">&#39;strings&#39;</span>)</div><div class="line">    <span class="keywordflow">if</span> (<span class="keywordflow">not</span> n.isSeq()):</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;strings is not a sequence! FAIL&#39;</span>, file=sys.stderr)</div><div class="line">        exit(1)</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(n.size()):</div><div class="line">        <span class="keywordflow">print</span> (n.at(i).string())</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    n = s.getNode(<span class="stringliteral">&#39;Mapping&#39;</span>)</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Two&#39;</span>,int(n.getNode(<span class="stringliteral">&#39;Two&#39;</span>).real()),<span class="stringliteral">&#39;; &#39;</span>)</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;One&#39;</span>,int(n.getNode(<span class="stringliteral">&#39;One&#39;</span>).real()),<span class="stringliteral">&#39;\n&#39;</span>)</div><div class="line">    </div><div class="line"></div><div class="line">    </div><div class="line">    R = s.getNode(<span class="stringliteral">&#39;R_MAT&#39;</span>).mat()</div><div class="line">    T = s.getNode(<span class="stringliteral">&#39;T_MAT&#39;</span>).mat()</div><div class="line">    </div><div class="line">    m.read(s.getNode(<span class="stringliteral">&#39;MyData&#39;</span>))</div><div class="line">    </div><div class="line"></div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;\nR =&#39;</span>,R)</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;T =&#39;</span>,T,<span class="stringliteral">&#39;\n&#39;</span>)</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;MyData =&#39;</span>,<span class="stringliteral">&#39;\n&#39;</span>,m,<span class="stringliteral">&#39;\n&#39;</span>)</div><div class="line"></div><div class="line">    </div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Attempt to read NonExisting (should initialize the data structure&#39;</span>,</div><div class="line">            <span class="stringliteral">&#39;with its default).&#39;</span>)</div><div class="line">    m.read(s.getNode(<span class="stringliteral">&#39;NonExisting&#39;</span>))</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;\nNonExisting =&#39;</span>,<span class="stringliteral">&#39;\n&#39;</span>,m)</div><div class="line">    </div><div class="line"></div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;\nTip: Open up&#39;</span>,filename,<span class="stringliteral">&#39;with a text editor to see the serialized data.&#39;</span>)</div><div class="line"></div><div class="line"><span class="keywordflow">if</span> __name__ == <span class="stringliteral">&#39;__main__&#39;</span>:</div><div class="line">    main(sys.argv)</div></div><!-- fragment -->  </div> <h2>Explanation </h2>
<p>Here we talk only about XML and YAML file inputs. Your output (and its respective input) file may have only one of these extensions and the structure coming from this. They are two kinds of data structures you may serialize: <em>mappings</em> (like the STL map and the Python dictionary) and <em>element sequence</em> (like the STL vector). The difference between these is that in a map every element has a unique name through what you may access it. For sequences you need to go through them to query a specific item.</p>
<ol type="1">
<li><p class="startli"><b>XML/YAML File Open and Close.</b> Before you write any content to such file you need to open it and at the end to close it. The XML/YAML data structure in OpenCV is <a class="el" href="../../da/d56/classcv_1_1FileStorage.html">cv::FileStorage</a> . To specify that this structure to which file binds on your hard drive you can use either its constructor or the <em><a class="el" href="../../d6/dee/group__hdf5.html#ga243d7e303690af3c5c3686ca5785205e" title="Open or create hdf5 file. ">open()</a></em> function of this: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        FileStorage fs(filename, FileStorage::WRITE);</div><div class="line">        <span class="comment">// or:</span></div><div class="line">        <span class="comment">// FileStorage fs;</span></div><div class="line">        <span class="comment">// fs.open(filename, FileStorage::WRITE);</span></div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    s = <a class="code" href="../../da/d56/classcv_1_1FileStorage.html">cv.FileStorage</a>(filename, cv.FileStorage_WRITE)</div><div class="line">    <span class="comment"># or:</span></div><div class="line">    <span class="comment"># s = cv.FileStorage()</span></div><div class="line">    <span class="comment"># s.open(filename, cv.FileStorage_WRITE)</span></div></div><!-- fragment --> </div> <p> Either one of this you use the second argument is a constant specifying the type of operations you'll be able to on them: WRITE, READ or APPEND. The extension specified in the file name also determinates the output format that will be used. The output may be even compressed if you specify an extension such as *.xml.gz*.</p>
<p class="startli">The file automatically closes when the <a class="el" href="../../da/d56/classcv_1_1FileStorage.html">cv::FileStorage</a> objects is destroyed. However, you may explicitly call for this by using the <em>release</em> function: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        fs.<a class="code" href="../../da/d56/classcv_1_1FileStorage.html#ad23d5415a06fb4bc97bfa034589b376e">release</a>();                                       <span class="comment">// explicit close</span></div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    s.release()</div></div><!-- fragment --> </div> </li>
<li><b>Input and Output of text and numbers.</b> In C++, the data structure uses the &lt;&lt; output operator in the STL library. In Python, <a class="el" href="../../da/d56/classcv_1_1FileStorage.html#a3efd38c576bac8b66281826f0a2642e7">cv::FileStorage::write()</a> is used instead. For outputting any type of data structure we need first to specify its name. We do this by just simply pushing the name of this to the stream in C++. In Python, the first parameter for the write function is the name. For basic types you may follow this with the print of the value :  <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;iterationNr&quot;</span> &lt;&lt; 100;</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    s.write(<span class="stringliteral">&#39;iterationNr&#39;</span>, 100)</div></div><!-- fragment --> </div>  Reading in is a simple addressing (via the [] operator) and casting operation or a read via the &gt;&gt; operator. In Python, we address with getNode() and use real() :  <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        <span class="keywordtype">int</span> itNr;</div><div class="line">        <span class="comment">//fs[&quot;iterationNr&quot;] &gt;&gt; itNr;</span></div><div class="line">        itNr = (int) fs[<span class="stringliteral">&quot;iterationNr&quot;</span>];</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">        <span class="keywordtype">int</span> itNr;</div><div class="line">        <span class="comment">//fs[&quot;iterationNr&quot;] &gt;&gt; itNr;</span></div><div class="line">        itNr = (int) fs[<span class="stringliteral">&quot;iterationNr&quot;</span>];</div></div><!-- fragment --> </div> </li>
<li><b>Input/Output of OpenCV Data structures.</b> Well these behave exactly just as the basic C++ and Python types:  <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        Mat R = <a class="code" href="../../df/dfc/classcv_1_1Mat__.html#a992daefd1a256fbd40423a2cf77f42a1">Mat_&lt;uchar&gt;::eye</a>(3, 3),</div><div class="line">            T = <a class="code" href="../../df/dfc/classcv_1_1Mat__.html#ab68de1358f5aedd6028269f77a9e841b">Mat_&lt;double&gt;::zeros</a>(3, 1);</div></div><!-- fragment --> <div class="fragment"><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;R&quot;</span> &lt;&lt; R;                                      <span class="comment">// cv::Mat</span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;T&quot;</span> &lt;&lt; T;</div></div><!-- fragment --> <div class="fragment"><div class="line">        fs[<span class="stringliteral">&quot;R&quot;</span>] &gt;&gt; R;                                      <span class="comment">// Read cv::Mat</span></div><div class="line">        fs[<span class="stringliteral">&quot;T&quot;</span>] &gt;&gt; T;</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    R = np.eye(3,3)</div><div class="line">    T = np.zeros((3,1))</div></div><!-- fragment --> <div class="fragment"><div class="line">    s.write(<span class="stringliteral">&#39;R_MAT&#39;</span>, R)</div><div class="line">    s.write(<span class="stringliteral">&#39;T_MAT&#39;</span>, T)</div></div><!-- fragment --> <div class="fragment"><div class="line">    R = s.getNode(<span class="stringliteral">&#39;R_MAT&#39;</span>).mat()</div><div class="line">    T = s.getNode(<span class="stringliteral">&#39;T_MAT&#39;</span>).mat()</div></div><!-- fragment --> </div> </li>
<li><p class="startli"><b>Input/Output of vectors (arrays) and associative maps.</b> As I mentioned beforehand, we can output maps and sequences (array, vector) too. Again we first print the name of the variable and then we have to specify if our output is either a sequence or map.</p>
<p class="startli">For sequence before the first element print the "[" character and after the last one the "]" character. With Python, call <code>FileStorage.startWriteStruct(structure_name, struct_type)</code>, where <code>struct_type</code> is <code>cv2.FileNode_MAP</code> or <code>cv2.FileNode_SEQ</code> to start writing the structure. Call <code>FileStorage.endWriteStruct()</code> to finish the structure: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;strings&quot;</span> &lt;&lt; <span class="stringliteral">&quot;[&quot;</span>;                              <span class="comment">// text - string sequence</span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;image1.jpg&quot;</span> &lt;&lt; <span class="stringliteral">&quot;Awesomeness&quot;</span> &lt;&lt; <span class="stringliteral">&quot;../data/baboon.jpg&quot;</span>;</div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;]&quot;</span>;                                           <span class="comment">// close sequence</span></div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    s.startWriteStruct(<span class="stringliteral">&#39;strings&#39;</span>, cv.FileNode_SEQ)</div><div class="line">    <span class="keywordflow">for</span> elem <span class="keywordflow">in</span> [<span class="stringliteral">&#39;image1.jpg&#39;</span>, <span class="stringliteral">&#39;Awesomeness&#39;</span>, <span class="stringliteral">&#39;../data/baboon.jpg&#39;</span>]:</div><div class="line">        s.write(<span class="stringliteral">&#39;&#39;</span>, elem)</div><div class="line">    s.endWriteStruct()</div></div><!-- fragment --> </div> <p> For maps the drill is the same however now we use the "{" and "}" delimiter characters: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;Mapping&quot;</span>;                              <span class="comment">// text - mapping</span></div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;{&quot;</span> &lt;&lt; <span class="stringliteral">&quot;One&quot;</span> &lt;&lt; 1;</div><div class="line">        fs &lt;&lt;        <span class="stringliteral">&quot;Two&quot;</span> &lt;&lt; 2 &lt;&lt; <span class="stringliteral">&quot;}&quot;</span>;</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    s.startWriteStruct(<span class="stringliteral">&#39;Mapping&#39;</span>, cv.FileNode_MAP)</div><div class="line">    s.write(<span class="stringliteral">&#39;One&#39;</span>, 1)</div><div class="line">    s.write(<span class="stringliteral">&#39;Two&#39;</span>, 2)</div><div class="line">    s.endWriteStruct()</div></div><!-- fragment --> </div> <p> To read from these we use the <a class="el" href="../../de/dd9/classcv_1_1FileNode.html">cv::FileNode</a> and the <a class="el" href="../../d7/d4e/classcv_1_1FileNodeIterator.html">cv::FileNodeIterator</a> data structures. The [] operator of the <a class="el" href="../../da/d56/classcv_1_1FileStorage.html">cv::FileStorage</a> class (or the getNode() function in Python) returns a <a class="el" href="../../de/dd9/classcv_1_1FileNode.html">cv::FileNode</a> data type. If the node is sequential we can use the <a class="el" href="../../d7/d4e/classcv_1_1FileNodeIterator.html">cv::FileNodeIterator</a> to iterate through the items. In Python, the <a class="el" href="../../d5/d50/group__videostab.html#ga64715f89ad837e2b6b5649d0f833172d">at()</a> function can be used to address elements of the sequence and the <a class="el" href="../../df/d5b/namespacecv_1_1gapi_1_1streaming.html#a0a915e69f4cc8284293e40fc9ffbf157" title="Gets dimensions from Mat. ">size()</a> function returns the length of the sequence: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        FileNode n = fs[<span class="stringliteral">&quot;strings&quot;</span>];                         <span class="comment">// Read string sequence - Get node</span></div><div class="line">        <span class="keywordflow">if</span> (n.type() != FileNode::SEQ)</div><div class="line">        {</div><div class="line">            cerr &lt;&lt; <span class="stringliteral">&quot;strings is not a sequence! FAIL&quot;</span> &lt;&lt; endl;</div><div class="line">            <span class="keywordflow">return</span> 1;</div><div class="line">        }</div><div class="line"></div><div class="line">        FileNodeIterator it = n.begin(), it_end = n.end(); <span class="comment">// Go through the node</span></div><div class="line">        <span class="keywordflow">for</span> (; it != it_end; ++it)</div><div class="line">            cout &lt;&lt; (<span class="keywordtype">string</span>)*it &lt;&lt; endl;</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    n = s.getNode(<span class="stringliteral">&#39;strings&#39;</span>)</div><div class="line">    <span class="keywordflow">if</span> (<span class="keywordflow">not</span> n.isSeq()):</div><div class="line">        <span class="keywordflow">print</span> (<span class="stringliteral">&#39;strings is not a sequence! FAIL&#39;</span>, file=sys.stderr)</div><div class="line">        exit(1)</div><div class="line"></div><div class="line">    <span class="keywordflow">for</span> i <span class="keywordflow">in</span> range(n.size()):</div><div class="line">        <span class="keywordflow">print</span> (n.at(i).string())</div></div><!-- fragment --> </div> <p> For maps you can use the [] operator (<a class="el" href="../../d5/d50/group__videostab.html#ga64715f89ad837e2b6b5649d0f833172d">at()</a> function in Python) again to access the given item (or the &gt;&gt; operator too): </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        n = fs[<span class="stringliteral">&quot;Mapping&quot;</span>];                                <span class="comment">// Read mappings from a sequence</span></div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Two  &quot;</span> &lt;&lt; (int)(n[<span class="stringliteral">&quot;Two&quot;</span>]) &lt;&lt; <span class="stringliteral">&quot;; &quot;</span>;</div><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;One  &quot;</span> &lt;&lt; (int)(n[<span class="stringliteral">&quot;One&quot;</span>]) &lt;&lt; endl &lt;&lt; endl;</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    n = s.getNode(<span class="stringliteral">&#39;Mapping&#39;</span>)</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Two&#39;</span>,int(n.getNode(<span class="stringliteral">&#39;Two&#39;</span>).real()),<span class="stringliteral">&#39;; &#39;</span>)</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;One&#39;</span>,int(n.getNode(<span class="stringliteral">&#39;One&#39;</span>).real()),<span class="stringliteral">&#39;\n&#39;</span>)</div></div><!-- fragment --> </div> </li>
<li><p class="startli"><b>Read and write your own data structures.</b> Suppose you have a data structure such as: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line"><span class="keyword">class </span>MyData</div><div class="line">{</div><div class="line"><span class="keyword">public</span>:</div><div class="line">      MyData() : A(0), X(0), id() {}</div><div class="line"><span class="keyword">public</span>:   <span class="comment">// Data Members</span></div><div class="line">   <span class="keywordtype">int</span> A;</div><div class="line">   <span class="keywordtype">double</span> X;</div><div class="line">   <span class="keywordtype">string</span> id;</div><div class="line">};</div></div><!-- fragment -->  </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line"><span class="keyword">class </span>MyData:</div><div class="line">    <span class="keyword">def </span>__init__(self):</div><div class="line">        self.A = self.X = 0</div><div class="line">        self.name = <span class="stringliteral">&#39;&#39;</span></div></div><!-- fragment -->  </div> <p> In C++, it's possible to serialize this through the OpenCV I/O XML/YAML interface (just as in case of the OpenCV data structures) by adding a read and a write function inside and outside of your class. In Python, you can get close to this by implementing a read and write function inside the class. For the inside part: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordtype">void</span> <a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a26447446dd3fa0644684a045e16399fe">write</a>(FileStorage&amp; fs) <span class="keyword">const</span>                        <span class="comment">//Write serialization for this class</span></div><div class="line">    {</div><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;{&quot;</span> &lt;&lt; <span class="stringliteral">&quot;A&quot;</span> &lt;&lt; A &lt;&lt; <span class="stringliteral">&quot;X&quot;</span> &lt;&lt; X &lt;&lt; <span class="stringliteral">&quot;id&quot;</span> &lt;&lt; <span class="keywordtype">id</span> &lt;&lt; <span class="stringliteral">&quot;}&quot;</span>;</div><div class="line">    }</div><div class="line">    <span class="keywordtype">void</span> <a class="code" href="../../de/dd9/classcv_1_1FileNode.html#ab24433dde37f770766481a91983e5f44">read</a>(<span class="keyword">const</span> FileNode&amp; node)                          <span class="comment">//Read serialization for this class</span></div><div class="line">    {</div><div class="line">        A = (int)node[<span class="stringliteral">&quot;A&quot;</span>];</div><div class="line">        X = (double)node[<span class="stringliteral">&quot;X&quot;</span>];</div><div class="line">        <span class="keywordtype">id</span> = (string)node[<span class="stringliteral">&quot;id&quot;</span>];</div><div class="line">    }</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="keyword">def </span><a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a26447446dd3fa0644684a045e16399fe">write</a>(self, fs, name):</div><div class="line">        fs.startWriteStruct(name, cv.FileNode_MAP|cv.FileNode_FLOW)</div><div class="line">        fs.write(<span class="stringliteral">&#39;A&#39;</span>, self.A)</div><div class="line">        fs.write(<span class="stringliteral">&#39;X&#39;</span>, self.X)</div><div class="line">        fs.write(<span class="stringliteral">&#39;name&#39;</span>, self.name)</div><div class="line">        fs.endWriteStruct()</div><div class="line"></div><div class="line">    <span class="keyword">def </span><a class="code" href="../../de/dd9/classcv_1_1FileNode.html#ab24433dde37f770766481a91983e5f44">read</a>(self, node):</div><div class="line">        <span class="keywordflow">if</span> (<span class="keywordflow">not</span> node.empty()):</div><div class="line">            self.A = int(node.getNode(<span class="stringliteral">&#39;A&#39;</span>).real())</div><div class="line">            self.X = node.getNode(<span class="stringliteral">&#39;X&#39;</span>).real()</div><div class="line">            self.name = node.getNode(<span class="stringliteral">&#39;name&#39;</span>).string()</div><div class="line">        <span class="keywordflow">else</span>:</div><div class="line">            self.A = self.X = 0</div><div class="line">            self.name = <span class="stringliteral">&#39;&#39;</span></div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'><p> In C++, you need to add the following functions definitions outside the class: </p><div class="fragment"><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="../../da/d56/classcv_1_1FileStorage.html#a26447446dd3fa0644684a045e16399fe">write</a>(FileStorage&amp; fs, <span class="keyword">const</span> std::string&amp;, <span class="keyword">const</span> MyData&amp; x)</div><div class="line">{</div><div class="line">    x.write(fs);</div><div class="line">}</div><div class="line"><span class="keyword">static</span> <span class="keywordtype">void</span> <a class="code" href="../../de/dd9/classcv_1_1FileNode.html#ab24433dde37f770766481a91983e5f44">read</a>(<span class="keyword">const</span> FileNode&amp; node, MyData&amp; x, <span class="keyword">const</span> MyData&amp; default_value = MyData()){</div><div class="line">    <span class="keywordflow">if</span>(node.empty())</div><div class="line">        x = default_value;</div><div class="line">    <span class="keywordflow">else</span></div><div class="line">        x.read(node);</div><div class="line">}</div></div><!-- fragment --> </div> <p> Here you can observe that in the read section we defined what happens if the user tries to read a non-existing node. In this case we just return the default initialization value, however a more verbose solution would be to return for instance a minus one value for an object ID.</p>
<p class="startli">Once you added these four functions use the &gt;&gt; operator for write and the &lt;&lt; operator for read (or the defined input/output functions for Python): </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        MyData m(1);</div></div><!-- fragment --> <div class="fragment"><div class="line">        fs &lt;&lt; <span class="stringliteral">&quot;MyData&quot;</span> &lt;&lt; m;                                <span class="comment">// your own data structures</span></div></div><!-- fragment --> <div class="fragment"><div class="line">        fs[<span class="stringliteral">&quot;MyData&quot;</span>] &gt;&gt; m;                                 <span class="comment">// Read your own structure_</span></div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    m = MyData()</div></div><!-- fragment --> <div class="fragment"><div class="line">    m.write(s, <span class="stringliteral">&#39;MyData&#39;</span>)</div></div><!-- fragment --> <div class="fragment"><div class="line">    m.read(s.getNode(<span class="stringliteral">&#39;MyData&#39;</span>))</div></div><!-- fragment --> </div> <p> Or to try out reading a non-existing read: </p> <div class='newInnerHTML' title='cpp' style='display: none;'>C++</div><div class='toggleable_div label_cpp' style='display: none;'> <div class="fragment"><div class="line">        cout &lt;&lt; <span class="stringliteral">&quot;Attempt to read NonExisting (should initialize the data structure with its default).&quot;</span>;</div><div class="line">        fs[<span class="stringliteral">&quot;NonExisting&quot;</span>] &gt;&gt; m;</div><div class="line">        cout &lt;&lt; endl &lt;&lt; <span class="stringliteral">&quot;NonExisting = &quot;</span> &lt;&lt; endl &lt;&lt; m &lt;&lt; endl;</div></div><!-- fragment --> </div>   <div class='newInnerHTML' title='python' style='display: none;'>Python</div><div class='toggleable_div label_python' style='display: none;'> <div class="fragment"><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;Attempt to read NonExisting (should initialize the data structure&#39;</span>,</div><div class="line">            <span class="stringliteral">&#39;with its default).&#39;</span>)</div><div class="line">    m.read(s.getNode(<span class="stringliteral">&#39;NonExisting&#39;</span>))</div><div class="line">    <span class="keywordflow">print</span> (<span class="stringliteral">&#39;\nNonExisting =&#39;</span>,<span class="stringliteral">&#39;\n&#39;</span>,m)</div></div><!-- fragment --> </div> </li>
</ol>
<h2>Result </h2>
<p>Well mostly we just print out the defined numbers. On the screen of your console you could see: </p><div class="fragment"><div class="line">Write Done.</div><div class="line"></div><div class="line">Reading:</div><div class="line">100image1.jpg</div><div class="line">Awesomeness</div><div class="line">baboon.jpg</div><div class="line">Two  2; One  1</div><div class="line"></div><div class="line"></div><div class="line">R = [1, 0, 0;</div><div class="line">  0, 1, 0;</div><div class="line">  0, 0, 1]</div><div class="line">T = [0; 0; 0]</div><div class="line"></div><div class="line">MyData =</div><div class="line">{ id = mydata1234, X = 3.14159, A = 97}</div><div class="line"></div><div class="line">Attempt to read NonExisting (should initialize the data structure with its default).</div><div class="line">NonExisting =</div><div class="line">{ id = , X = 0, A = 0}</div><div class="line"></div><div class="line">Tip: Open up output.xml with a text editor to see the serialized data.</div></div><!-- fragment --><p> Nevertheless, it's much more interesting what you may see in the output xml file: </p><div class="fragment"><div class="line">&lt;?<span class="keyword">xml</span> <span class="keyword">version</span>=<span class="stringliteral">&quot;1.0&quot;</span>?&gt;</div><div class="line">&lt;<span class="keywordtype">opencv_storage</span>&gt;</div><div class="line">&lt;<span class="keywordtype">iterationNr</span>&gt;100&lt;/<span class="keywordtype">iterationNr</span>&gt;</div><div class="line">&lt;<span class="keywordtype">strings</span>&gt;</div><div class="line">  <span class="keyword">image1.jpg</span> <span class="keyword">Awesomeness</span> <span class="keyword">baboon.jpg</span>&lt;/<span class="keywordtype">strings</span>&gt;</div><div class="line">&lt;<span class="keywordtype">Mapping</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">One</span>&gt;1&lt;/<span class="keywordtype">One</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">Two</span>&gt;2&lt;/<span class="keywordtype">Two</span>&gt;&lt;/<span class="keywordtype">Mapping</span>&gt;</div><div class="line">&lt;<span class="keywordtype">R</span> <span class="keyword">type_id</span>=<span class="stringliteral">&quot;opencv-matrix&quot;</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">rows</span>&gt;3&lt;/<span class="keywordtype">rows</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">cols</span>&gt;3&lt;/<span class="keywordtype">cols</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">dt</span>&gt;<span class="keyword">u</span>&lt;/<span class="keywordtype">dt</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">data</span>&gt;</div><div class="line">    1 0 0 0 1 0 0 0 1&lt;/<span class="keywordtype">data</span>&gt;&lt;/<span class="keywordtype">R</span>&gt;</div><div class="line">&lt;<span class="keywordtype">T</span> <span class="keyword">type_id</span>=<span class="stringliteral">&quot;opencv-matrix&quot;</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">rows</span>&gt;3&lt;/<span class="keywordtype">rows</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">cols</span>&gt;1&lt;/<span class="keywordtype">cols</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">dt</span>&gt;<span class="keyword">d</span>&lt;/<span class="keywordtype">dt</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">data</span>&gt;</div><div class="line">    0. 0. 0.&lt;/<span class="keywordtype">data</span>&gt;&lt;/<span class="keywordtype">T</span>&gt;</div><div class="line">&lt;<span class="keywordtype">MyData</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">A</span>&gt;97&lt;/<span class="keywordtype">A</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">X</span>&gt;3.1415926535897931<span class="keyword">e</span>+000&lt;/<span class="keywordtype">X</span>&gt;</div><div class="line">  &lt;<span class="keywordtype">id</span>&gt;<span class="keyword">mydata1234</span>&lt;/<span class="keywordtype">id</span>&gt;&lt;/<span class="keywordtype">MyData</span>&gt;</div><div class="line">&lt;/<span class="keywordtype">opencv_storage</span>&gt;</div></div><!-- fragment --><p> Or the YAML file: </p><div class="fragment"><div class="line">%YAML:1.0</div><div class="line">iterationNr: 100</div><div class="line">strings:</div><div class="line">   - &quot;image1.jpg&quot;</div><div class="line">   - Awesomeness</div><div class="line">   - &quot;baboon.jpg&quot;</div><div class="line">Mapping:</div><div class="line">   One: 1</div><div class="line">   Two: 2</div><div class="line">R: !!opencv-matrix</div><div class="line">   rows: 3</div><div class="line">   cols: 3</div><div class="line">   dt: u</div><div class="line">   data: [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ]</div><div class="line">T: !!opencv-matrix</div><div class="line">   rows: 3</div><div class="line">   cols: 1</div><div class="line">   dt: d</div><div class="line">   data: [ 0., 0., 0. ]</div><div class="line">MyData:</div><div class="line">   A: 97</div><div class="line">   X: 3.1415926535897931e+000</div><div class="line">   id: mydata1234</div></div><!-- fragment --><p> You may observe a runtime instance of this on the <a href="https://www.youtube.com/watch?v=A4yqVnByMMM">YouTube here</a> .</p>
<div align='center'><iframe title='Video' width='560' height='349' src='https://www.youtube.com/embed/A4yqVnByMMM?rel=0' frameborder='0' align='middle' allowfullscreen></iframe></div> </div></div><!-- contents -->
<!-- HTML footer for doxygen 1.8.6-->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Fri Apr 2 2021 11:36:34 for OpenCV by &#160;<a href="http://www.doxygen.org/index.html">
<img class="footer" src="../../doxygen.png" alt="doxygen"/>
</a> 1.8.13
</small></address>
<script type="text/javascript">
//<![CDATA[
addTutorialsButtons();
//]]>
</script>
</body>
</html>
